package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingBaseRateEntity;
import com.ly.heart.mapper.KingBaseCurrencyMapper;
import com.ly.heart.service.IKingBaseCurrencyService;
import com.ly.heart.service.IKingBaseRateService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import com.ly.heart.domain.KingBaseCurrencyEntity;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 金蝶-基础数据-币别-推金蝶Service业务层处理
 *
 * @author wutao
 * @date 2024-06-19
 */
@Service
public class KingBaseCurrencyServiceImpl extends ServiceImpl<KingBaseCurrencyMapper, KingBaseCurrencyEntity> implements IKingBaseCurrencyService {

    @Resource
    private ISysDeptService iSysDeptService;
    @Resource
    private IKingBaseRateService iKingBaseRateService;

    /**
     * 查询金蝶-基础数据-币别-推金蝶
     *
     * @param id 金蝶-基础数据-币别-推金蝶ID
     * @return 金蝶-基础数据-币别-推金蝶
     */
    @Override
    public KingBaseCurrencyEntity selectKingBaseCurrencyEntityById ( String id ) {
        KingBaseCurrencyEntity baseCurrencyEntity = this.getById ( id );
        return baseCurrencyEntity;
    }

    /**
     * 查询金蝶-基础数据-币别-推金蝶列表
     * 币别对应的汇率：
     * 查询所选币别是否等于系统本位币，如是则直接给1，否则查询币别对应的汇率
     *
     * @param kingBaseCurrencyEntity 金蝶-基础数据-币别-推金蝶
     * @return 金蝶-基础数据-币别-推金蝶
     */
    @Override
    public Page selectKingBaseCurrencyEntityList ( KingBaseCurrencyEntity kingBaseCurrencyEntity ) {
        SysDept sysDept = iSysDeptService.getById ( CurrentUserUtil.getCompanyId () );
        Page<KingBaseCurrencyEntity> page = this.page ( new Page<> ( kingBaseCurrencyEntity.getPage (), kingBaseCurrencyEntity.getLimit () ), new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getIsUsed, ConstUtil.IS_USED_YES ) );
        List<KingBaseCurrencyEntity> kingBaseCurrencyEntities = page.getRecords ();
        //提取所有币别的编码
        List<String> codes = kingBaseCurrencyEntities.stream ().map ( KingBaseCurrencyEntity :: getCode ).collect ( Collectors.toList () );
        if ( ! CollectionUtils.isEmpty ( codes ) ) {
            List<KingBaseRateEntity> list = iKingBaseRateService.list ( new LambdaQueryWrapper<KingBaseRateEntity> ().in ( KingBaseRateEntity :: getId, codes ) );
            kingBaseCurrencyEntities.forEach ( currency -> {
                if ( ! currency.getCode ().equals ( sysDept.getStandardCurrencyCode () ) ) {
                    //根据当前币别查询今天在汇率有效期内的汇率
                    List<KingBaseRateEntity> rateEntities = list.stream ().filter ( rate -> currency.getCode ().equals (
                            rate.getSourceCurrency () ) &&
                            rate.getEffectiveTime ().before ( DateUtils.getNowDate () ) &&
                            rate.getInvalidTime ().after ( DateUtils.getNowDate () ) ).
                            collect ( Collectors.toList () );
                    if ( rateEntities != null && rateEntities.size () > 0 )
                        currency.setRate ( rateEntities.get ( 0 ).getDirectRate () );
                }
            } );
        }
        page.setRecords ( kingBaseCurrencyEntities );
        return page;
    }

    /**
     * 新增金蝶-基础数据-币别-推金蝶
     *
     * @param kingBaseCurrencyEntity 金蝶-基础数据-币别-推金蝶
     * @return 结果
     */
    @Override
    public AjaxResult insertKingBaseCurrencyEntity ( KingBaseCurrencyEntity kingBaseCurrencyEntity ) {
        kingBaseCurrencyEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        kingBaseCurrencyEntity.setCode ( "PRE".concat ( String.format ( "%08d", count ) ) );
        kingBaseCurrencyEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        kingBaseCurrencyEntity.setCreateTime ( DateUtils.getNowDate () );
        boolean save = this.save ( kingBaseCurrencyEntity );
        if ( ! save ) {
            throw new CustomException ( "新增币别失败！" );
        }
        return AjaxResult.success ( "新增币别成功" );
    }

    /**
     * 修改金蝶-基础数据-币别-推金蝶
     *
     * @param kingBaseCurrencyEntity 金蝶-基础数据-币别-推金蝶
     * @return 结果
     */
    @Override
    public AjaxResult updateKingBaseCurrencyEntity ( KingBaseCurrencyEntity kingBaseCurrencyEntity ) {
        kingBaseCurrencyEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        kingBaseCurrencyEntity.setUpdateTime ( DateUtils.getNowDate () );
        boolean b = this.updateById ( kingBaseCurrencyEntity );
        if ( ! b ) {
            throw new CustomException ( "修改币别失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 批量删除金蝶-基础数据-币别-推金蝶
     *
     * @param ids 需要删除的金蝶-基础数据-币别-推金蝶ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingBaseCurrencyEntityByIds ( String[] ids ) {
        List<KingBaseCurrencyEntity> list = this.list ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().in ( KingBaseCurrencyEntity :: getId, ids ) );
        List<String> idList = list.stream ().filter ( currency -> currency.getIsDel () == 1 ).map ( KingBaseCurrencyEntity :: getId ).collect ( Collectors.toList () );
        StringBuilder stringBuilder = new StringBuilder ( "【" );
        list.forEach ( currency -> {
            if ( currency.getIsDel () == 2 ) {
                stringBuilder.append ( currency.getCurrencyName () );
            }
        } );
        stringBuilder.append ( "】" );
        //删除前先检查是否有被引用
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseCurrencyEntity> ().
                set ( KingBaseCurrencyEntity :: getIsUsed, ConstUtil.IS_USED_NO ).
                set ( KingBaseCurrencyEntity :: getUpdateTime, DateUtils.getNowDate () ).
                set ( KingBaseCurrencyEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                in ( KingBaseCurrencyEntity :: getId, idList ) );
        if ( ! update ) {
            throw new CustomException ( "删除币别失败！" );
        }
        String str = "删除币别成功";
        if ( list.size () > 0 ) {
            str.concat ( "，其中" ).concat ( stringBuilder.toString () ).concat ( "被引用，不可删除" );
        }
        return AjaxResult.success ( str );
    }

    /**
     * 禁用/反禁用
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult disable ( String id ) {
        KingBaseCurrencyEntity currencyEntity = this.getById ( id );
        if ( currencyEntity == null ) {
            throw new CustomException ( "无此币别！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseCurrencyEntity> ().
                set ( KingBaseCurrencyEntity :: getIsDisabled, currencyEntity.getIsDisabled () == 1 ? 2 : 1 ).
                set ( KingBaseCurrencyEntity :: getUpdateTime, DateUtils.getNowDate () ).
                set ( KingBaseCurrencyEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                eq ( KingBaseCurrencyEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( currencyEntity.getIsDisabled () == 1 ? "禁用币别失败！" : "解禁币别失败！" );
        }
        return AjaxResult.success ( currencyEntity.getIsDisabled () == 1 ? "禁用币别成功" : "解禁币别成功" );
    }

}
